Page({
  data: {
    images: [],
    title: '',
    content: '',
    visibilities: ['公开', '仅自己可见', '好友可见'],
    visibility: '公开'
  },

  onBack() {
    wx.navigateBack();
  },

  onAddImage() {
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const list = this.data.images.concat(res.tempFilePaths);
        this.setData({ images: list.slice(0, 9) });
      }
    });
  },

  onTitleInput(e) { this.setData({ title: e.detail.value }); },
  onContentInput(e) { this.setData({ content: e.detail.value }); },
  onVisChange(e) { this.setData({ visibility: this.data.visibilities[e.detail.value] }); },

  onSubmit() {
    if (!this.data.title || !this.data.content) {
      wx.showToast({ title: '请填写标题和内容', icon: 'none' });
      return;
    }
    const app = getApp();
    const user = app?.globalData?.userInfo || { name: '用户', avatar: 'https://dummyimage.com/120x120/cccccc/888888.png&text=U' };
    const now = new Date();
    const time = `${now.getMonth() + 1}月${now.getDate()}日`;
    const newPost = {
      id: Date.now(),
      user: { name: user.name || '用户', avatar: user.avatar },
      time,
      title: this.data.title,
      content: this.data.content,
      images: this.data.images,
      likes: 0,
      comments: 0,
      views: 0,
      visibility: this.data.visibility
    };

    try {
      const list = wx.getStorageSync('circle_posts') || [];
      list.unshift(newPost);
      wx.setStorageSync('circle_posts', list);
      wx.showToast({ title: '发布成功', icon: 'success' });
      setTimeout(() => wx.navigateBack(), 600);
    } catch (e) {
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  }
});
